const { notarize } = require('electron-notarize');

const fs = require('fs')
const path = require('path')
const yaml = require('js-yaml');
const dotenv = require('dotenv');

exports.default = async function notarizing(context) {
  const {electronPlatformName, appOutDir} = context;

  if (electronPlatformName !== 'darwin') {
    return;
  }

  const appName = context.packager.appInfo.productFilename;
  const yamlDoc = yaml.load(fs.readFileSync(path.resolve(process.cwd(), 'electron-builder.yml'), 'utf8'));
 
  const envFilePath = path.resolve(process.cwd(), 'mac/.env.'+appName);
  console.log(envFilePath)
  let envConfig = {}
  if (fs.existsSync(envFilePath)) {
    envConfig = dotenv.parse(fs.readFileSync(envFilePath, 'utf8')); 
    process.env.APPLETEAMID = envConfig.APPLETEAMID;
    process.env.APPLEID = envConfig.APPLEID;
    process.env.APPLEIDPASSWORD = envConfig.APPLEIDPASSWORD;
  } else {
    console.warn(`Warning: The ${appName} Mac App config file does not exist at ${envFilePath}`);

  }

  return await notarize({
    tool: 'notarytool',
    teamId: process.env.APPLETEAMID,
    appBundleId: yamlDoc.appId,
    appPath: `${appOutDir}/${appName}.app`,
    appleId: process.env.APPLEID,
    appleIdPassword: process.env.APPLEIDPASSWORD,
  });
};
